// Bristleback plugin - Copyright (c) 2010 bristleback.googlecode.com
// ---------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
// This library is distributed in the hope that it will be useful,
// but without any warranty; without even the implied warranty of merchantability
// or fitness for a particular purpose.
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
// ---------------------------------------------------------------------------
package pl.bristleback.server.bristle.states;

import org.apache.log4j.Logger;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * This class contains queue with server state listeners.
 * <p/>
 * Created on: 2010-10-14 18:18:08 <br/>
 *
 * @author Wojciech Niemiec
 */
public final class ServerStateListenerChain {
  private static Logger log = Logger.getLogger(ServerStateListenerChain.class.getName());

  private List<ServerStateListener> listeners;

  private boolean processListeners;

  /**
   * Creates a new empty server state listener chain.
   */
  public ServerStateListenerChain() {
    listeners = new LinkedList<ServerStateListener>();
  }

  /**
   * Starts a chain, iterating on all listeners and invokes their {@code onServerStart(this)} method.
   * If any listener calls {@code cancelChain()} method on this chain, then processing will be stopped.
   */
  public void serverStart() {
    processListeners = true;
    Iterator<ServerStateListener> it = listeners.iterator();
    while (processListeners && it.hasNext()) {
      it.next().onServerStart(this);
    }
  }

  /**
   * Starts a chain, iterating on all listeners and invokes their {@code onServerStop(this)} method.
   * If any listener calls {@code cancelChain()} method on this chain, then processing will be stopped.
   */
  public void serverShutdown() {
    processListeners = true;
    Iterator<ServerStateListener> it = listeners.iterator();
    while (processListeners && it.hasNext()) {
      it.next().onServerStop(this);
    }
  }

  /**
   * Cancels server state listeners processing, any next remaining listeners won't be processed.
   */
  public void cancelChain() {
    processListeners = false;
  }

  /**
   * Adds a server state listener to the chain.
   *
   * @param listener server state listener.
   */
  public void addListener(ServerStateListener listener) {
    listeners.add(listener);
  }
}
